//
//  DetailController.m
//  敢唆嘛!
//
//  Created by lanou on 15/11/24.
//  Copyright © 2015年 zms. All rights reserved.
//

#import "DetailController.h"
#import "Device.h"
#import "DetailCell.h"
#import "DetailHeader.h"
#import "ChineseToPinyin.h"
#import "RecommendController.h"
#import "CommentsController.h"
//#import "DetailFooter.h"

typedef NS_ENUM(NSInteger, CollectState)
{
    collectOn,
    collectOff
};

typedef NS_ENUM(NSInteger, DownTapState)
{
    downTapOpen,
    downTapClose
};

@interface DetailController ()<UITableViewDataSource,UITableViewDelegate>
{
    // 底部按钮视图轻拍状态
    DownTapState downTapState;
    
    // 收藏和取消收藏状态
    CollectState collectState;
}

@property(nonatomic , strong)UITableView *tableView;

//底部弹出View各控件
@property(nonatomic , strong)UIView *bottomView;//底部视图
@property(nonatomic , strong)UIButton *recommendBtn;//推荐按钮
@property(nonatomic , strong)UIButton *collectionBtn;//收藏按钮
@property(nonatomic , strong)UIButton *commentsBtn;//评论按钮
@property(nonatomic , strong)UIButton *shareBtn;//分享按钮
@property(nonatomic, strong)UILabel *collectionLabel; // 收藏数
@property(nonatomic, strong)UILabel *shareLabel;        // 分享数
@property(nonatomic, strong)NSString *reloadState; //收藏刷新状态
@property(nonatomic, strong)UIView *promptView;     // 提示视图
@property(nonatomic, strong)UILabel *titleLabel;    // 提示标题
@property(nonatomic, strong)UIImageView *collectionImageView;   // 收藏的图片
@property(nonatomic, strong)BmobUser *bmobUser;         // 用户
@property(nonatomic, strong)NSString *collectObjectId;  // 记录收藏表内id
@property(nonatomic, strong)UIView *jubaoView;
@end
static NSString *cellIndentifier = @"cell";
@implementation DetailController
{
    CGFloat  lastContentOffset;
    BOOL isScroll;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = YES;
//    self.navigationController.navigationBar.hidden = NO;
    
    // 添加举报按钮
    UIButton *jubaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    jubaoBtn.frame = CGRectMake(0, 0, KSWidth / 18, KSWidth / 18);
    [jubaoBtn setImage:[UIImage imageNamed:@"iconfont-jubaoyoujian"] forState:UIControlStateNormal];
    [jubaoBtn addTarget:self action:@selector(jubaoBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftjubaoBtn = [[UIBarButtonItem alloc] initWithCustomView:jubaoBtn];
    self.navigationItem.rightBarButtonItem = leftjubaoBtn;
    
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSWidth / 2.5, KSWidth / 25)];
    // 顶部类型图标
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake((topView.frame.size.width - KSWidth / 26) / 1.5, topView.frame.size.height - KSWidth / 20, KSWidth / 26, KSWidth / 26)];
    icon.image = [UIImage imageNamed:@"iconfont-jiantou"];
    [topView addSubview:icon];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((topView.frame.size.width - KSWidth / 26) / 2.8 , topView.frame.size.height - KSWidth / 17, KSWidth / 8, KSWidth / 28)];
    titleLabel.text = @"封面";
    titleLabel.alpha = 0.8;
    titleLabel.font = [UIFont systemFontOfSize:KSWidth / 22];
    [topView addSubview:titleLabel];
    self.navigationItem.titleView = topView;
    
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    //注册cell
    [self.tableView registerClass:[DetailCell class] forCellReuseIdentifier:cellIndentifier];
    //注册表头
    [self.tableView registerClass:[DetailHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
//    [self.tableView registerClass:[DetailFooter class] forHeaderFooterViewReuseIdentifier:@"footer"];
    [self.view addSubview:self.tableView];
    
    // 创建左上角返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, KSWidth / 18, KSWidth / 18);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-unie61e"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBackBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftBackBtn;
    
    // 初始化状态
    downTapState = downTapOpen;
  

//    底部弹出视图
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, KSHeight - space*4, KSWidth, space*4)];
    self.bottomView.backgroundColor = [UIColor whiteColor];
//    灰色线条
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, 0.5)];
    lineView.backgroundColor = [UIColor blackColor];
    lineView.alpha = 0.3;

//    推荐按钮
    self.recommendBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.recommendBtn.frame = CGRectMake(0, 0, KSWidth/4, space*4);
    [self.recommendBtn addTarget:self action:@selector(recommendBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    图片
    UIImageView *recommendImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KSWidth/10, space/4*3, KSWidth/20, space*1.2)];
    recommendImageView.image = [UIImage imageNamed:@"iconfont-xunhuan2Black"];
    [self.recommendBtn addSubview:recommendImageView];
//    推荐数
    UILabel *recommendLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, space*2.2 ,KSWidth/4, space)];
    recommendLabel.textAlignment = NSTextAlignmentCenter;
    recommendLabel.font = [UIFont systemFontOfSize:10];
    [self.recommendBtn addSubview:recommendLabel];
    

//    收藏按钮
    self.collectionBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collectionBtn.frame = CGRectMake(KSWidth/4, 0, KSWidth/4, space*4);
    [self.collectionBtn addTarget:self action:@selector(collectionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//    图片
    self.collectionImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KSWidth/10, space/4*3, KSWidth/20, space*1.2)];
    [self.collectionBtn addSubview:_collectionImageView];
//    收藏数
    self.collectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, space*2.2 ,KSWidth/4, space)];
//    collectionLabel.text = @"收藏(10)";
    self.collectionLabel.textAlignment = NSTextAlignmentCenter;
    self.collectionLabel.font = [UIFont systemFontOfSize:10];
    [self.collectionBtn addSubview:_collectionLabel];
    

//    评论按钮
    self.commentsBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.commentsBtn.frame = CGRectMake(KSWidth/2, 0, KSWidth/4, space*4);
    [self.commentsBtn addTarget:self action:@selector(commentsBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //    图片
    UIImageView *commentsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KSWidth/10, space/4*3, KSWidth/20, space*1.2)];
    commentsImageView.image = [UIImage imageNamed:@"iconfont-duihuaqipaoBlack"];
    [self.commentsBtn addSubview:commentsImageView];
    //    评论数
    UILabel *commentsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, space*2.2 ,KSWidth/4, space)];
//    commentsLabel.text = @"评论(100)";
    commentsLabel.textAlignment = NSTextAlignmentCenter;
    commentsLabel.font = [UIFont systemFontOfSize:10];
    [self.commentsBtn addSubview:commentsLabel];
    
//    分享按钮
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.shareBtn.frame = CGRectMake(KSWidth/4*3, 0, KSWidth/4, space*4);
    [self.shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //    图片
    UIImageView *shareImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KSWidth/10, space/4*3, KSWidth/20, space*1.2)];
    shareImageView.image = [UIImage imageNamed:@"iconfont-fenxiang"];
    [self.shareBtn addSubview:shareImageView];
    //    分享数
    self.shareLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, space*2.2 ,KSWidth/4, space)];
//    shareLabel.text = @"分享(0)";
    self.shareLabel.textAlignment = NSTextAlignmentCenter;
    self.shareLabel.font = [UIFont systemFontOfSize:10];
    [self.shareBtn addSubview:_shareLabel];
    
    NSInteger recommendNumber = 0;
    NSInteger collectNumber = 0;
    NSInteger commentNumber = 0;
    NSInteger shareNumber = 0;
    // 设置值
    if (self.homeModel)
    {
        recommendNumber = self.homeModel.recommendNumber;
        collectNumber = self.homeModel.collectNumber;
        commentNumber = self.homeModel.commentNumber;
        shareNumber = self.homeModel.shareNumber;
    }
    else
    {
        recommendNumber = self.realityModel.recommendNumber;
        collectNumber = self.realityModel.collectNumber;
        commentNumber = self.realityModel.commentNumber;
        shareNumber = self.realityModel.shareNumber;
    }
    recommendLabel.text = [NSString stringWithFormat:@"推荐(%ld)",recommendNumber];
    self.collectionLabel.text = [NSString stringWithFormat:@"收藏(%ld)",collectNumber];
    commentsLabel.text = [NSString stringWithFormat:@"评论(%ld)",commentNumber];
    self.shareLabel.text = [NSString stringWithFormat:@"分享(%ld)",shareNumber];
    

    [self.bottomView addSubview:self.recommendBtn];
    [self.bottomView addSubview:self.collectionBtn];
    [self.bottomView addSubview:self.commentsBtn];
    [self.bottomView addSubview:self.shareBtn];
    [self.bottomView addSubview:lineView];
    [self.view addSubview:self.bottomView];
    
    
// 轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    // 每次进来先到数据库内找该用户的收藏列表内是否有这个收藏,如果有就替换收藏图标
    [self isFindUserCollection];
    
}

// 举报按钮触发事件
- (void)jubaoBtnAction:(UIButton *)jubaoBtn
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    if (!_bmobUser)
    {
        [self alertActionWithTitle:@"提示" message:@"登录后才能使用该功能" other:@"确定"];
    }
    else
    {
        // 弹框提示
        [self jubaoViewWithTitle:@"您确定要举报这篇文章吗?" okStr:@"确定" cancelStr:@"取消"];
    }
}

// 提示view
- (void)jubaoViewWithTitle:(NSString *)content okStr:(NSString *)okStr cancelStr:(NSString *)cancelStr
{
    // 关闭按钮交互
    self.navigationController.navigationBar.userInteractionEnabled = NO;
    self.jubaoView = [[UIView alloc] initWithFrame:CGRectMake((KSWidth - (KSWidth / 1.5)) / 2, KSWidth - KSWidth / 3, KSWidth / 1.5, KSWidth / 3)];
    self.jubaoView.backgroundColor = [UIColor whiteColor];
    self.jubaoView.layer.cornerRadius = 10;
    self.jubaoView.layer.borderColor = [UIColor colorWithRed:150 / 255.0 green:150 / 255.0 blue:150 / 255.0 alpha:1.0].CGColor;
    self.jubaoView.layer.borderWidth = 1;
    [self.view addSubview:_jubaoView];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(KSWidth / 37.5, KSWidth / 37.5, _jubaoView.frame.size.width - (KSWidth / 37.5) *2, _jubaoView.frame.size.width / 12.5)];
    title.text = @"提示";
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = [UIColor blackColor];
    title.font = [UIFont systemFontOfSize:KSWidth / 25];
    [_jubaoView addSubview:title];
    
    UILabel *info = [[UILabel alloc] initWithFrame:CGRectMake(KSWidth / 37.5, title.frame.size.height + (KSWidth / 37.5) * 2, _jubaoView.frame.size.width - (KSWidth / 37.5) *2, _jubaoView.frame.size.width / 12.5)];
    info.text = content;
    info.textAlignment = NSTextAlignmentCenter;
    info.textColor = [UIColor blackColor];
    info.font = [UIFont systemFontOfSize:KSWidth / 25];
    [_jubaoView addSubview:info];
    
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeSystem];
    okButton.frame = CGRectMake((KSWidth / 37.5) * 4, title.frame.size.height + info.frame.size.height + (KSWidth / 37.5) * 4, KSWidth / 7.5, KSWidth / 12.5);
    [okButton setTitle:okStr forState:UIControlStateNormal];
    [okButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [okButton addTarget:self action:@selector(okButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    cancelButton.frame = CGRectMake(okButton.frame.size.width + (KSWidth / 37.5) * 11, title.frame.size.height + info.frame.size.height + (KSWidth / 37.5) * 4, KSWidth / 7.5, KSWidth / 12.5);
    [cancelButton setTitle:cancelStr forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_jubaoView addSubview:cancelButton];
    
    if (!okStr)
    {
        cancelButton.frame = CGRectMake(okButton.frame.size.width + (KSWidth / 37.5) * 5, title.frame.size.height + info.frame.size.height + (KSWidth / 37.5) * 4, KSWidth / 7.5, KSWidth / 12.5);
    }
    else
    {
        [_jubaoView addSubview:okButton];
    }
    

}

// 根据用户名添加一个收藏表和数据
- (void)addJuBao
{
    //根据用户名添加一个该用户单独的收藏表
    BmobObject *userJuBao = [BmobObject objectWithClassName:@"JuBao"];
    
    NSString *userName = nil;
    NSString *infoTitle = nil;
    NSString *info = nil;
    NSString *type = nil;
    if (self.homeModel)
    {
        userName = self.homeModel.userName;
        infoTitle = self.homeModel.infoTitle;
        info = self.homeModel.info;
        type = self.homeModel.type;
        [userJuBao setObject:self.homeModel.realityCreatedAt forKey:@"realityCreatedAt"];
    }
    else
    {
        userName = self.realityModel.userName;
        infoTitle = self.realityModel.infoTitle;
        info = self.realityModel.type;
        type = self.realityModel.objectId;
    }
    [userJuBao setObject:userName forKey:@"userName"];
    [userJuBao setObject:infoTitle forKey:@"infoTitle"];
    [userJuBao setObject:info forKey:@"info"];
    [userJuBao setObject:type forKey:@"type"];
    [userJuBao saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        //进行操作
        if (isSuccessful)
        {
            NSLog(@"成功");
            [self jubaoViewWithTitle:@"举报成功" okStr:nil cancelStr:@"确定"];
            self.navigationController.navigationBar.userInteractionEnabled = YES;
        }
        else
        {
            NSLog(@"失败");
            NSLog(@"%@",error);
            self.navigationController.navigationBar.userInteractionEnabled = YES;
        }
    }];
}


- (void)okButtonAction:(UIButton *)okButton
{
    // 写入数据库
    [self.jubaoView removeFromSuperview];
    [self addJuBao];
}

- (void)cancelButtonAction:(UIButton *)cancelButton
{
    [self.jubaoView removeFromSuperview];
    self.navigationController.navigationBar.userInteractionEnabled = YES;
}

// 返回按钮触发
- (void)backBtnAction:(UIButton *)backBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 轻拍手势事件 显示下面视图 或者隐藏下面视图
-(void)tapAction:(UITapGestureRecognizer *)tap
{
//    self.navigationController.navigationBar.hidden = !self.navigationController.navigationBar.hidden;
    
    if (downTapState == downTapClose)
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.bottomView.frame = CGRectMake(0, KSHeight - space*4, KSWidth, space*4);
        }];
        downTapState = downTapOpen;
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.bottomView.frame = CGRectMake(0, KSHeight, KSWidth, space*4);
        }];
        downTapState = downTapClose;
    }

}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = YES;
}

// 进入该界面后
- (void)viewDidAppear:(BOOL)animated
{
//    self.navigationController.navigationBar.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.bottomView.frame = CGRectMake(0, KSHeight, KSWidth, space*4);
    }];
    //底部视图的状态先是close 关闭
    downTapState = downTapClose;
}

//  判断tableview是往上滑动还是往下滑动
-(void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    isScroll = YES;
    //开始滚动的y值
    lastContentOffset = scrollView.contentOffset.y;
}

-( void )scrollViewDidScroll:( UIScrollView *)scrollView
{
    if (isScroll)
    {
        //如果已经滚动的y值 比开始滚动的y值要小 说明是向上滚动的
        if (scrollView. contentOffset.y < lastContentOffset )
        {
            //向上
            NSLog(@"shang");
//            self.navigationController.navigationBar.hidden = NO;
            [UIView animateWithDuration:0.3 animations:^{
                self.bottomView.frame = CGRectMake(0, KSHeight - space*4, KSWidth, space*4);
            }];
            downTapState = downTapOpen;
            
        }
        else if (scrollView. contentOffset.y > lastContentOffset )
        {
            //向下
//            self.navigationController.navigationBar.hidden = YES;
            [UIView animateWithDuration:0.3 animations:^{
                self.bottomView.frame = CGRectMake(0, KSHeight, KSWidth, space*4);
            }];
            downTapState = downTapClose;
            NSLog(@"xia");
        }
    }
}

// 返回是哪个表的数据
- (NSString *)tableClassName
{
    NSString *className = nil;
#warning 判断页面
    if (self.homeModel)
    {
        if ([self.homeModel.type isEqualToString:@"真事"])
        {
            className = @"Reality";
        }
        else if ([self.homeModel.type isEqualToString:@"创作"])
        {
            className = @"Creation";
        }
        else if ([self.homeModel.type isEqualToString:@"游记"])
        {
            className = @"Travel";
        }
        else if ([self.homeModel.type isEqualToString:@"秘密"])
        {
            className = @"Secret";
        }
    }
    else
    {
        if ([self.realityModel.type isEqualToString:@"真事"])
        {
            className = @"Reality";
        }
        else if ([self.realityModel.type isEqualToString:@"创作"])
        {
            className = @"Creation";
        }
        else if ([self.realityModel.type isEqualToString:@"游记"])
        {
            className = @"Travel";
        }
        else if ([self.realityModel.type isEqualToString:@"秘密"])
        {
            className = @"Secret";
        }
    }
    return className;
}

// 点击推荐按钮触发方法
- (void)recommendBtnAction:(UIButton *)recommendBtn
{
    // 判断当前用户是否登录中
    self.bmobUser = [BmobUser getCurrentUser];
    if (_bmobUser)
    {
        // 进入推荐界面
        RecommendController *recommendVc = [[RecommendController alloc] init];
        if (self.homeModel)
        {
            recommendVc.homeModel = self.homeModel;
        }
        else
        {
            recommendVc.realityModel = self.realityModel;
        }
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationController pushViewController:recommendVc animated:YES];
    }
    else
    {
        [self promptViewWithTitle:@"请先登录哟~" buttonEnabled:self.recommendBtn];
        // 需要做一个弹窗View进入登录界面
        
    }
}

// 点击分享按钮触发方法  这个是shareSDK 标准版
- (void)shareBtnAction:(UIButton *)shareBtn
{
    NSString *title = nil;
    NSString *info = nil;
    NSString *infoTitleImage = nil;
    
    if (self.homeModel)
    {
        title = self.homeModel.infoTitle;
        info = self.homeModel.info;
        infoTitleImage = self.homeModel.infoTitleImage;
    }
    else
    {
        title = self.realityModel.infoTitle;
        info = self.realityModel.info;
        infoTitleImage = self.realityModel.infoTitleImage;
    }
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:title
                                       defaultContent:title
                                                image:[ShareSDK imageWithUrl:infoTitleImage]
                                                title:title //qq空间标题
                                                  url:@"123" //不能中文 必须地址
                                          description:title //qq空间内容
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:self.view arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    [self promptViewWithTitle:@"分享成功" buttonEnabled:self.shareBtn];
                                    // 分享成功后 需要到数据库查找该条主题 给分享数 + 1
                                    [self updateRealityTableShare];

                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSString *errors = [NSString stringWithFormat:@"分享失败,错误码:%ld,错误描述:%@", [error errorCode], [error errorDescription]];
                                    NSLog(@"%@",errors);
                                    [self promptViewWithTitle:@"分享失败" buttonEnabled:self.shareBtn];
                                }
                            }];
}

// 点击收藏按钮触发方法
- (void)collectionBtnAction:(UIButton *)collectionBtn
{
    // 判断当前用户是否登录中
    self.bmobUser = [BmobUser getCurrentUser];
    if (_bmobUser)
    {
        // 判断当前状态
        if (collectState == collectOn)
        {
            // 取消收藏
// #warning 取消收藏
            [self findUserCollectionTableObjectId];
        }
        else
        {
            // 添加收藏
            [self addUserCollectionTable];
        }
    }
    else
    {
        [self promptViewWithTitle:@"请先登录哟~" buttonEnabled:self.shareBtn];
        // 需要做一个弹窗View进入登录界面
    }
}

// 点击评论按钮触发
- (void)commentsBtnAction:(UIButton *)commentsBtn
{
    // 判断当前用户是否登录中
    self.bmobUser = [BmobUser getCurrentUser];
    if (_bmobUser)
    {
        CommentsController *commentsVc = [[CommentsController alloc] init];
        if (self.homeModel)
        {
            commentsVc.homeModel = self.homeModel;
        }
        else
        {
            commentsVc.realityModel = self.realityModel;
        }
        
        [self.navigationController pushViewController:commentsVc animated:YES];
    }
    else
    {
        [self promptViewWithTitle:@"请先登录哟~" buttonEnabled:self.commentsBtn];
    }
}

// 根据用户名添加一个收藏表和数据
- (void)addUserCollectionTable
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    //根据用户名添加一个该用户单独的收藏表
    BmobObject *userCollection = [BmobObject objectWithClassName:[NSString stringWithFormat:@"%@Collection",string]];
    
    NSString *userName = nil;
    NSString *infoTitle = nil;
    NSString *info = nil;
    NSString *realityObjectId = nil;
    if (self.homeModel)
    {
        userName = self.homeModel.userName;
        infoTitle = self.homeModel.infoTitle;
        info = self.homeModel.info;
        realityObjectId = self.homeModel.realityObjectId;
        [userCollection setObject:self.homeModel.realityCreatedAt forKey:@"realityCreatedAt"];
    }
    else
    {
        userName = self.realityModel.userName;
        infoTitle = self.realityModel.infoTitle;
        info = self.realityModel.info;
        realityObjectId = self.realityModel.objectId;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";//日期格式
        NSString *dateS = [formatter stringFromDate:self.realityModel.createdAt];
        [userCollection setObject:dateS forKey:@"realityCreatedAt"];
    }
    [userCollection setObject:userName forKey:@"userName"];
    [userCollection setObject:infoTitle forKey:@"infoTitle"];
    [userCollection setObject:info forKey:@"info"];
    [userCollection setObject:realityObjectId forKey:@"realityObjectId"];
    [userCollection saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        //进行操作
        if (isSuccessful)
        {
            NSLog(@"成功");
            // 替换收藏图片
            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-2"];
            [self promptViewWithTitle:@"收藏成功~" buttonEnabled:self.collectionBtn];
            collectState = collectOn;
            // 写入到收藏数的数据表内
            [self updateRealityTableCollection];
        }
        else
        {
            NSLog(@"失败");
            NSLog(@"%@",error);
        }
    }];
}

//// 用户收藏数据库查询
//- (void)findUserCollectionData
//{
//    // 获取当前登录的用户
//    self.bmobUser = [BmobUser getCurrentUser];
//    // 把名字转化为拼音
//    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
//    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"%@Collection",string]];
//    //查找当前用户的收藏表的数据
//    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
//        // 判断收藏表内是否有数据存在
//        if (array.count == 0)
//        {
//            // 如果为0 就直接添加
//            [self addUserCollectionTable];
//        }
//        // 否则就进去查找是否有相同的
//        else
//        {
//            for (int i = 0; i < array.count; i++)
//            {
//                BmobObject *obj = array[i];
//                if (self.homeModel)
//                {
//                    // 调用方法添加这条数据
//                    [self addUserCollectionTable];
//                }
//                else
//                {
//                    // 判断当前主题的id是否在该用户的收藏表内存在,如果存在就不添加
//                    if (![self.realityModel.objectId isEqualToString:[obj objectForKey:@"realityObjectId"]])
//                    {
//                        if (i == array.count - 1)
//                        {
//                            // 调用方法添加这条数据
//                            NSLog(@"不存在这条数据");
//                            [self addUserCollectionTable];
//                        }
//                        else
//                        {
//                            NSLog(@"已经存在了,就删除掉");
//                            [self findUserCollectionTableObjectId];
//                        }
//                    }
//                    else
//                    {
//                        NSLog(@"已经存在了,就删除掉");
//                        [self findUserCollectionTableObjectId];
//                    }
//                }
//            }
//        }
//
//    }];
//}

// #warning 查询用户收藏表查询数据 获得objectId
- (void)findUserCollectionTableObjectId
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"%@Collection",string]];
    //查找当前用户的收藏表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (int i = 0; i < array.count; i++)
        {
            BmobObject *obj = array[i];
            if (self.homeModel)
            {
                // 判断当前主题的id是否在该用户的收藏表内存在,如果存在就不添加
                if ([self.homeModel.realityObjectId isEqualToString:[obj objectForKey:@"realityObjectId"]])
                {
                    // 存在数据 获取objectId
                    self.collectObjectId = [obj objectId];
                    // 删除
                    [self deleteUserCollectionTable];
                }
            }
            else
            {
                // 判断当前主题的id是否在该用户的收藏表内存在,如果存在就不添加
                if ([self.realityModel.objectId isEqualToString:[obj objectForKey:@"realityObjectId"]])
                {
                    // 存在数据 获取objectId
                    self.collectObjectId = [obj objectId];
                    // 删除
                    [self deleteUserCollectionTable];
                }

            }
        }
        
    }];
}

// #warning 根据用户名删除一个收藏表的数据
- (void)deleteUserCollectionTable
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:[NSString stringWithFormat:@"%@Collection",string]  objectId:_collectObjectId];
    
    [bmobObject deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            //删除成功后的动作
            NSLog(@"successful");
            // 替换收藏图片
            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-1"];
            [self promptViewWithTitle:@"取消收藏" buttonEnabled:self.collectionBtn];
            self.collectObjectId = nil;
            collectState = collectOff;
// #warning 更新收藏数
            [self updateRealityTableCollection];

        } else if (error){
            NSLog(@"%@",error);
        } else {
            NSLog(@"UnKnow error");
        }
    }];
}

// 更新 reality表内的指定主题的收藏数
- (void)updateRealityTableCollection
{
    NSString *collectObjectId = nil;
    if (self.homeModel)
    {
        collectObjectId = self.homeModel.realityObjectId;
    }
    else
    {
        collectObjectId = self.realityModel.objectId;
    }
    // 先获取到本来的收藏数是多少
    BmobQuery *bquery = [BmobQuery queryWithClassName:[self tableClassName]];
    [bquery getObjectInBackgroundWithId:collectObjectId block:^(BmobObject *object,NSError *error){
        if (error){
            //进行错误处理
        }else{
            if (object)
            {
                // 得到该条数据当前的收藏数是多少
                NSInteger number = 0;
                if (collectState == collectOn)
                {
                    number = [[object objectForKey:@"collectNumber"] integerValue] + 1;
                }
                else
                {
                    number = [[object objectForKey:@"collectNumber"] integerValue] - 1;
                }
                NSNumber *collectNumber = [NSNumber numberWithInteger:number];
                // 修改值
                BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:[self tableClassName]  objectId:collectObjectId];
                [bmobObject setObject:collectNumber forKey:@"collectNumber"];
                [bmobObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    if (isSuccessful) {
                        //修改成功后的动作
                        // 收藏数更新成功
                        NSLog(@"收藏数更新+1");
                        // 调用重新到数据库内加载数据
                        [self reloadRealityCollectData];
                        
                    } else if (error){
                        NSLog(@"%@",error);
                    } else {
                        NSLog(@"UnKnow error");
                    }
                }];
            }
        }
    }];
}

// 更新 reality表内的指定主题的分享数
- (void)updateRealityTableShare
{
    NSString *collectObjectId = nil;
    if (self.homeModel)
    {
        collectObjectId = self.homeModel.realityObjectId;
    }
    else
    {
        collectObjectId = self.realityModel.objectId;
    }
    // 先获取到本来的收藏数是多少
    BmobQuery *bquery = [BmobQuery queryWithClassName:[self tableClassName]];
    [bquery getObjectInBackgroundWithId:collectObjectId block:^(BmobObject *object,NSError *error){
        if (error){
            //进行错误处理
        }else{
            if (object)
            {
                // 得到该条数据当前的收藏数是多少
                NSInteger number = [[object objectForKey:@"shareNumber"] integerValue] + 1;
                NSNumber *shareNumber = [NSNumber numberWithInteger:number];
                // 修改值
                BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:[self tableClassName]  objectId:collectObjectId];
                [bmobObject setObject:shareNumber forKey:@"shareNumber"];
                [bmobObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    if (isSuccessful) {
                        //修改成功后的动作
                        // 收藏数更新成功
                        NSLog(@"分享数更新+1");
                        // 调用重新到数据库内加载数据
                        [self reloadRealityCollectData];
                        
                    } else if (error){
                        NSLog(@"%@",error);
                    } else {
                        NSLog(@"UnKnow error");
                    }
                }];
            }
        }
    }];
}


// 重新到数据库内加载数据
- (void)reloadRealityCollectData
{
    NSString *collectObjectId = nil;
    if (self.homeModel)
    {
        collectObjectId = self.homeModel.realityObjectId;
    }
    else
    {
        collectObjectId = self.realityModel.objectId;
    }

    BmobQuery *bquery = [BmobQuery queryWithClassName:[self tableClassName]];
    [bquery getObjectInBackgroundWithId:collectObjectId block:^(BmobObject *object,NSError *error){
        if (error){
            //进行错误处理
        }else{

            if (object) {
                if (self.homeModel)
                {
                    //给model赋值
                    self.homeModel.collectNumber = [[object objectForKey:@"collectNumber"] integerValue];
                    self.homeModel.shareNumber = [[object objectForKey:@"shareNumber"] integerValue];
                    NSLog(@"model更新");
                    
                    //给视图上的数据重新赋值
                    self.collectionLabel.text = [NSString stringWithFormat:@"收藏(%ld)",self.homeModel.collectNumber];
                    self.shareLabel.text = [NSString stringWithFormat:@"分享(%ld)",self.homeModel.shareNumber];
                }
                else
                {
                    self.realityModel.collectNumber = [[object objectForKey:@"collectNumber"] integerValue];
                    self.realityModel.shareNumber = [[object objectForKey:@"shareNumber"] integerValue];
                    NSLog(@"model更新");
                    self.collectionLabel.text = [NSString stringWithFormat:@"收藏(%ld)",self.realityModel.collectNumber];
                    self.shareLabel.text = [NSString stringWithFormat:@"分享(%ld)",self.realityModel.shareNumber];
                }
                // 通知home界面进行对collect刷新
                self.reloadState = @"reload";
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reload" object:self.reloadState];
            }
        }
    }];
}

// 每次进来先到数据库内找该用户的收藏列表内是否有这个收藏,如果有就替换收藏图标
- (void)isFindUserCollection
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"%@Collection",string]];
    //查找当前用户的收藏表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        // 判断收藏表内是否有数据存在
        if (array.count == 0)
        {
            // 设置收藏图片为可收藏
            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-1"];
            collectState = collectOff;
        }
        // 否则就进去查找是否有相同的
        else
        {
            for (int i = 0; i < array.count; i++)
            {
                BmobObject *obj = array[i];
                if (self.homeModel)
                {
                    // 判断当前主题的id是否在该用户的收藏表内存在,如果存在就不添加
                    if (![self.homeModel.realityObjectId isEqualToString:[obj objectForKey:@"realityObjectId"]])
                    {    //是最后一个的时候还是没收藏 说明是真的没收藏
                        if (i == array.count - 1)
                        {
                            // 设置收藏图片为可收藏
                            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-1"];
                            collectState = collectOff;
                        }
                        else
                        {
                            // 设置收藏图片为不可收藏 这个可以不写
                            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-2"];
                            collectState = collectOn;
//                            break;
                        }
                    }
                    else
                    {
                        // 设置收藏图片为不可收藏
                        self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-2"];
                        collectState = collectOn;
                        break; //找到了就跳出for循环
                    }
                }
                else
                {
                    // 判断当前主题的id是否在该用户的收藏表内存在,如果存在就不添加
                    if (![self.realityModel.objectId isEqualToString:[obj objectForKey:@"realityObjectId"]])
                    {
                        if (i == array.count - 1)
                        {
                            // 设置收藏图片为可收藏
                            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-1"];
                            collectState = collectOff;
                        }
                        else
                        {
                            // 设置收藏图片为不可收藏
                            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-2"];
                            collectState = collectOn;
//                            break;
                        }
                    }
                    else
                    {
                        // 设置收藏图片为不可收藏
                        self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-2"];
                        collectState = collectOn;
                        break; //找到了就跳出for循环
                    }
                }
            }
        }
        
    }];
}

// 弹出提示窗口
- (void)promptViewWithTitle:(NSString *)title buttonEnabled:(UIButton *)buttonEnabled
{
    // 关闭按钮交互
    buttonEnabled.userInteractionEnabled = NO;
    self.promptView = [[UIView alloc] initWithFrame:CGRectMake(-(KSWidth - (KSWidth / 2)) / 2, KSWidth - KSWidth / 4, KSWidth / 2, KSWidth / 4)];
    self.promptView.backgroundColor = [UIColor whiteColor];
    self.promptView.alpha = 0;
    self.promptView.layer.cornerRadius = 10;
    self.promptView.layer.borderColor = [UIColor colorWithRed:150 / 255.0 green:150 / 255.0 blue:150 / 255.0 alpha:1.0].CGColor;
    self.promptView.layer.borderWidth = 1;
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(-(KSWidth - (KSWidth / 2)) / 2, KSWidth - KSWidth / 4, KSWidth / 2, KSWidth / 4)];
    self.titleLabel.text = title;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.textColor = [UIColor blackColor];
    self.titleLabel.font = [UIFont systemFontOfSize:KSWidth / 25];
    self.titleLabel.alpha = 0;
    [self.view addSubview:_promptView];
    [self.view addSubview:self.titleLabel];
    
    [UIView animateWithDuration:0.4 animations:^{
        self.promptView.alpha = 0.8;
        self.titleLabel.alpha = 0.8;
        self.promptView.frame = CGRectMake((KSWidth - (KSWidth / 2)) / 2, KSWidth - KSWidth / 4, KSWidth / 2, KSWidth / 4);
        self.titleLabel.frame = CGRectMake((KSWidth - (KSWidth / 2)) / 2, KSWidth - KSWidth / 4, KSWidth / 2, KSWidth / 4);
    }completion:^(BOOL finished) {
        // 延迟一秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.4 animations:^{
                self.promptView.alpha = 0;
                self.titleLabel.alpha = 0;
                self.promptView.frame = CGRectMake(((KSWidth - (KSWidth / 2)) / 2) * 2, KSWidth - KSWidth / 4, KSWidth / 2, KSWidth / 4);
                self.titleLabel.frame = CGRectMake(((KSWidth - (KSWidth / 2)) / 2) * 2, KSWidth - KSWidth / 4, KSWidth / 2, KSWidth / 4);
            }completion:^(BOOL finished) {
                // 打开收藏按钮交互
                buttonEnabled.userInteractionEnabled = YES;
                [self.promptView removeFromSuperview];
            }];
        });
    }];
}

// 分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

//动态返回cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.homeModel)
    {
        return [DetailCell heightForHomeCell:self.homeModel];
    }
    else
    {
        return [DetailCell heightForRealityCell:self.realityModel];
    }
}

// 返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    
    if (self.homeModel)
    {
        [cell setHomeModel:self.homeModel];
    }
    else
    {
        [cell setRealityModel:self.realityModel];
    }
    
    return cell;
}

// 设置表头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return KSHeight;
}

// 表头设置
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    DetailHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    
    if (self.homeModel)
    {
        [header setHomeModel:self.homeModel];
    }
    else
    {
        [header setRealityModel:self.realityModel];
    }
    
    return header;
}


// 设置表尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

//// 表尾设置
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    DetailFooter *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
//    
//    return footer;
//}

// 弹出视图
- (void)alertActionWithTitle:(NSString *)title message:(NSString *)message other:(NSString *)other
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:nil];
    [alertVc addAction:otherAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
